<?php

declare(strict_types=1);

namespace app\model;

use app\common\facade\auth\Auth;
use app\common\service\auth\AuthAdminService;
use app\common\service\auth\AuthAgentService;
use app\common\service\auth\AuthApiService;
use app\common\service\order\coupon_order\coupon\CouponOrderBuild;
use app\common\service\order\CouponOrderService;
use app\model\base\BaseCouponProductChannelModel;
use think\facade\Log;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $name 产品渠道
 * @property int $supplier_id 供应商
 * @property string $origin_id 第三方id
 * @property int $product_id 产品id
 * @property int $sale_price 销售价
 * @property int $cost_price 成本价
 * @property int $market_price 市场价
 * @property string $extend 扩展字段存json
 * @property string $rule 规则说明
 * @property int $status 状态(1:启用,2:关闭)
 * @property string $created_at
 * @property string $updated_at
 * @property string $mark 第一次导入聚推客使用匹配，上线后可删除
 * @property-read \app\model\BaseSupplier $base_supplier
 * @property string $profit 预计佣金
 * @property string $type 所属供应商
 * @property bool $butt 与供应商是否对接
 * @property string $image 商品图片
 * @property int $brand_id 品牌id
 * @property bool $sku_type 货源商品类型 0 未分类 1 卡券商品 2 直充商品
 * @property bool $relate_state 关联状态 0未关联 1已关联 2匹配失败
 * @property bool $shelf_state 上下架状态 -1未知状态 0 下架 1上架
 * @property string $deleted_at 删除标识
 * @property-read \app\model\CouponProduct $coupon_product
 * @property-read \app\model\CouponBrand $brand
 * @property-read \app\model\CouponConfig $coupon_config
 * @property-read bool|string $sale_price_text
 * @property-read mixed $sales_volume
 * @property-read \app\model\CouponProduct $product
 * @property-read mixed $cost_price_text
 * @property-read mixed $const_premium_rate
 * @property-read \app\model\CouponCate[] $coupon_cate
 * @property-read mixed $match_relate_state_result
 * @property-read mixed $share_profit_save
 * @method static \think\db\Query availableSale()
 * @property int $advance_time 调价生效时间，时间戳
 * @property int $advance_price 调价价格
 * @property-read mixed $buy_input_rule
 * @property-read \app\model\CouponExtension $coupon_extension
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class CouponProductChannel extends BaseCouponProductChannelModel
{
    use SoftDelete;

    const STATUS_ACTIVE = 1; //激活
    const STATUS_CLOSE = 0; //关闭

    //供应商
    const TYPE_JTK = 'jutuike';  //聚推客
    const TYPE_YQD = 'YiQiDa';   //亿奇达
    const TYPE_JC = 'JingChong'; //鲸充

    //是否对接
    const BUTT_ACTIVE = 1;       //已对接
    const BUTT_CLOSE = 0;       //未对接

    //商品类型
    const SKU_TYPE_WFL = 0;      //未分类
    const SKU_TYPE_KQ = 1;      //卡券
    const SKU_TYPE_ZC = 2;      //直充

    //匹配状态
    const RELETE_STATE_WPP = 0;  //未匹配
    const RELETE_STATE_YPP = 1;  //已匹配
    const RELETE_STATE_PPSB = 2;  //匹配失败

    //上下架状态
    const SHELF_STATE_WZ = -1;    //未知状态
    const SHELF_STATE_XZ = 0;     //已下架
    const SHELF_STATE_SZ = 1;     //上架

    //转换溢价后的销售价使用，请勿删除变更
    public $agent_id; //代理id
    public $is_agent; //1 是否代理后台或者用户端
    public $premiumRate = [];

    //商品类型
    public static $skuType = [
        ['sku_type' => '0', 'name' => '未分类'],
        ['sku_type' => '1', 'name' => '卡券'],
        ['sku_type' => '2', 'name' => '直充'],
    ];
    //货源的商品状态
    public static $skuState = [
        ['status' => '0', 'name' => '已失效'],
        ['status' => '1', 'name' => '正常'],
    ];
    //匹配状态
    public static $relateState = [
        ['relate_state' => '0', 'name' => '未匹配'],
        ['relate_state' => '1', 'name' => '已匹配'],
        ['relate_state' => '2', 'name' => '匹配失败'],
    ];
    //上下架状态
    public static $shelfState = [
        ['shelf_state' => '-1', 'name' => '未上架'],
        ['shelf_state' => '0', 'name' => '已下架'],
        ['shelf_state' => '1', 'name' => '已上架'],
    ];
    //对接状态
    public static $buttState = [
        ['butt' => '0', 'name' => '未对接'],
        ['butt' => '1', 'name' => '已对接'],
    ];


    public function couponExtension()
    {
        return $this->hasOne(CouponExtension::class, 'obj_id','product_id')->where('type', CouponExtension::TYPE_PRODUCT)->where('agent_id',Auth::agentId());
    }

    //各个下拉框数组
    public static function getStatus()
    {
        return [
            'sku_type' => self::$skuType,
            'sku_state' => self::$skuState,
            'shelf_state' => self::$shelfState,
            'relate_state' => self::$relateState,
            'buttState' => self::$buttState,
        ];
    }

    public function baseSupplier()
    {
        return $this->hasOne(BaseSupplier::class, "id", "supplier_id")
            ->field("id,name")
            ->setOption('soft_delete', null); //删除的供应商还显示在后台列表中展示
    }

    //商品状态获取器
//    public function getStatusAttr($value)
//    {
//        $status = [0 => '已失效', 1 => '正常'];
//        return $status[$value];
//    }
//
//    //商品类型获取器
//    public function getSkuTypeAttr($value)
//    {
//        $status = [0 => '未分类', 1 => '卡券', 2 => '直充'];
//        return $status[$value];
//    }
//
//    //匹配状态获取器
//    public function getRelateStateAttr($value)
//    {
//        $status = [0 => '未对接', 1 => '已对接', 2 => '匹配失败'];
//        return $status[$value];
//    }
//    //上下架状态获取器
//    public function getShelfStateAttr($value)
//    {
//        $status = [-1 => '未知初始状态', 0 => '已下架', 1 => '已上架'];
//        return $status[$value];
//    }

    /**
     * 获取货源对接列表
     * @param array $params
     * @return array
     */
    public function productChannelList($params)
    {
        $key = $params['key'] ?? '';
        $supplierId = $params['supplier_id'] ?? '';
        $butt = (isset($params['butt']) && in_array($params['butt'], [0, 1])) ? $params['butt'] : '';
        $list = self::when($key, function ($query) use ($key) {
            $query->where('name|id', 'like', '%' . $key . "%");
        })->when($supplierId, function ($query) use ($supplierId) {
            $query->where('supplier_id', $supplierId);
        })->when($butt != '', function ($query) use ($butt) {
            $query->where('butt', $butt);
        })->with(['baseSupplier', 'brand' => function ($query) {
            $query->where('status', self::STATUS_ACTIVE)->withOutField('deleted_at, cate_id, sort, created_at, updated_at')->with(['couponCate' => function ($query) {
                //$query->where('status', CouponCate::STATUS_ACTIVE);
            }]);
        }])->where('type', '<>', self::TYPE_JTK)
            ->where('butt', self::BUTT_CLOSE)
            ->where('status', self::STATUS_ACTIVE)
            ->order('id DESC')
            ->append(['sales_volume'])
            ->paginate()
            ->toArray();
        return $list;
    }

    //销售数量
    public function getSalesVolumeAttr($value, $couponProductChannel)
    {
        //销量需要和产品确认定义
        return CouponOrder::where('quote_id', $couponProductChannel['id'])->where('status', CouponOrder::C_STATUS_RECHARGE_SUCCESS)->count();
    }

    /**
     * 获取货源对接列表
     * @access public
     * @return object
     */
    public function couponProduct()
    {
        return $this->belongsTo(CouponProduct::class, 'product_id', 'id')->with('brandType');
    }

    public function product()
    {
        return $this->belongsTo(CouponProduct::class, 'product_id', 'id');
    }

    /**
     * 批量上下架
     * @access public
     */
    public function shelfState($shelf_state, $idArr)
    {
        //1.未对接商品或者已失效不允许上下架
        $existsIdArr = self::query()
            ->whereIn('id', $idArr)
            ->select();
        $unNormalStatus = array();
        if ($shelf_state == self::SHELF_STATE_SZ) {
            foreach ($existsIdArr as $productChannls) {
                if ($productChannls->status == self::STATUS_CLOSE || $productChannls->relate_state != self::RELETE_STATE_YPP) {
                    $unNormalStatus[] = $productChannls->id;
                }
            }
        }
        $successNum = 0;
        $normalArr = array_diff($idArr, $unNormalStatus);
        if ($normalArr) {
            foreach ($normalArr as $id) {
                /**
                 * @var CouponProductChannel $info
                 */
                $info = self::query()->where('id', $id)->find();
                if (!$info) {
                    continue;
                }
                $info->shelf_state = $shelf_state;
                if ($info->save()) {
                    //记录操作日志
                    if ($shelf_state == self::SHELF_STATE_XZ) {
                        Log::info('主动下架商品' . $info->id);
                    }
                    $successNum++;
                }
            }
        }
        $str = $shelf_state ? '上架' : '下架';
        if ($successNum == 0) {
            return fail('全部商品' . $str . '失败');
        }
        return success($successNum . '个商品' . $str . '成功');
    }


    //获取直充商品列表
    public function getList($param)
    {
        $key = isset($param['key']) ? trim($param['key']) : '';
        //是否代理端
        $is_agent = $param['is_agent'] ?? 0;
        //代理id
        $agent_id = $param['agent_id'] ?? 0;
        $map = array();
        if (isset($param['status']) && $param['status'] != '') {
            $map[] = ['status', '=', $param['status']];
        }
        if (isset($param['shelf_state']) && $param['shelf_state'] != '') {
            $map[] = ['shelf_state', '=', $param['shelf_state']];
        }
        if (isset($param['relate_state']) && $param['relate_state'] != '') {
            $map[] = ['relate_state', '=', $param['relate_state']];
        }
        if (isset($param['supplier_id']) && $param['supplier_id'] != '') {
            $map[] = ['supplier_id', '=', $param['supplier_id']];
        }
        return self::query()->where($map)->when($key, function ($query) use ($key) {
            $query->where('id|name', 'like', '%' . $key . '%');
        })->with(['baseSupplier', 'brand' => function ($query) {
                $query->where('status', CouponBrand::STATUS_ACTIVE)->with(['couponCate' => function ($query) {

                }]);
            }, 'product' => function ($query) {
                $query->where('status', CouponProduct::STATUS_ACTIVE)->field('id,name,type_id');
            }]
        )->where('butt', self::BUTT_ACTIVE)
            ->where('type', '<>', self::TYPE_JTK)
            ->withoutField('extend, mark, type, deleted_at, butt')
            ->append(['real_sale_price'])
            ->order('updated_at desc')
            ->paginate()
            ->each(function (CouponProductChannel $couponProductChannel) use ($agent_id, $is_agent) {
                if (!$couponProductChannel->isEmpty()) {
                    $couponProductChannel->agent_id = $agent_id;
                    $couponProductChannel->is_agent = $is_agent;
                    if ($is_agent == 1) {
                        $couponProductChannel->append(['sale_price_text', 'cost_price_text', 'match_relate_state_result']);
                    } else {
                        $couponProductChannel->append(['sale_price_text', 'match_relate_state_result']);
                    }
                }
            })->toArray();
    }

    //品牌
    public function brand()
    {
        return $this->hasOne(CouponBrand::class, "id", "brand_id");
    }

    public function doEdit($params)
    {
        $id = $params['id'];
        $cate_id = isset($params['cate_id']) ? $params['cate_id'] : 0;
        $brand_id = $params['brand_id'];
        $type_id = $params['type_id'];
        $product_id = $params['product_id'];
        $rule = isset($params['rule']) ? $params['rule'] : '';
        //查询本直充商品是否存在
        $info = self::where('status', self::STATUS_ACTIVE)->where('id', $id)->findOrEmpty();
        if ($info->isEmpty()) {
            return fail('商品已不存在或者已经失效');
        }
        //查询商品分类是否启动或者删除
        $cate = CouponCate::where('status', CouponCate::STATUS_ACTIVE)->where('id', $cate_id)->findOrEmpty();
//        if ($cate->isEmpty()) {
//            return fail('商品分类已不存在');
//        }
        //查询品牌名称是否启动或者删除
        $brand = CouponBrand::where('status', CouponBrand::STATUS_ACTIVE)->where('id', $brand_id)->findOrEmpty();
        if ($brand->isEmpty()) {
            return fail('品牌名称已不存在');
        }
        //查询充值类型是否启动或者删除
        $brand_type = CouponBrandType::where('status', CouponBrandType::STATUS_ACTIVE)->where('id', $type_id)->findOrEmpty();
        if ($brand_type->isEmpty()) {
            return fail('充值类型已不存在');
        }
        //查询充值面额是否启动或者删除
        $product = CouponProduct::where('status', CouponProduct::STATUS_ACTIVE)->where('id', $product_id)->findOrEmpty();
        if ($product->isEmpty()) {
            return fail('充值面额已不存在');
        }
        $info->product_id = $product_id;
        $info->brand_id = $brand_id;
        $info->relate_state = self::RELETE_STATE_YPP;
        $info->rule = $rule;
        if ($info->save()) {
            return success('编辑成功', ['id' => $params['id']]);
        }
        return fail('编辑失败');
    }

    //以产品设置为coupon_config
    public function couponConfig()
    {
        return $this->hasOne(CouponConfig::class, 'quote_id', 'product_id');
    }

    /**
     * 获取溢价后的销售价
     * @param $value
     * @param $model
     * @return false|string
     */
    public function getSalePriceTextAttr($value, $model)
    {
        $auth = Auth::instance();
        //H5端
        if ($auth instanceof AuthApiService) {
            $this->agent_id = Auth::agentId();
            $this->is_agent = 1;
        } elseif ($auth instanceof AuthAgentService) { //代理端

        } elseif ($auth instanceof AuthAdminService) {//后台

        } else {
            //...
        }
        $service = new CouponOrderService();
        $result = $service->calculateThePrice($this->id, $this->agent_id, $this->premiumRate);
        if ($this->is_agent == 1) {
            return (float)$result->getPayAmount(); //支付价格(加上代理溢价后的价格)
        }
        return (float)$result->getSettlePrice();   //成本价(平台溢价后的价格)
    }

    //分享节省
    public function getShareProfitSaveAttr($value, $model)
    {
        $newCouponOrder = new CouponOrder();
        $newCouponOrder->quote_id = $model['id'];
        $buildService = new CouponOrderBuild($newCouponOrder);
        return $buildService->profit;
    }

    /**
     * 代理看到的结算价
     * @param $value
     * @param $model
     * @return false|string
     */
    public function getCostPriceTextAttr($value, $model)
    {
        $service = new CouponOrderService();
        $result = $service->calculateThePrice($this->id, $this->agent_id);
        return (float)$result->getSettlePrice();
    }

    //费率
    public function getConstPremiumRateAttr($value, $model)
    {
        $configModel = new Config();
        return $configModel->getPremiunRate();
    }


    public function couponCate()
    {
        return $this->belongsToMany(CouponCate::class, 'coupon_brand_cate_relation', 'cate_id', 'brand_id');
    }

    //根据查询条件判断是否存在
    public function queryDataByCondition($map)
    {
        return self::query()->where($map)->find();
    }

    public function getMatchRelateStateResultAttr($value, $model)
    {
        if ($model['relate_state'] == 1) {
            $res = CouponProduct::query()->where('id', $model['product_id'])->with(['brandType' => function ($query) {
                    $query->with(['brand' => function ($query) {
                        $query->field('id,name');
                    }])->field('id,name,brand_id');
                }]
            )->field('id, name, brand_id, type_id')->findOrEmpty()->toArray();
            $relate_name = '';
            if (isset($res['brandType']['brand']['name'])) {
                $relate_name .= $res['brandType']['brand']['name'];
            }
            if (isset($res['brandType']['name'])) {
                $relate_name .= '_' . $res['brandType']['name'];
            }

            if (isset($res['name'])) {
                $relate_name .= '_' . $res['name'];
            }
            return $relate_name;
        }
    }

    //批量删除------批量从直充商品状态变成货源对接状态
    public function btachRecovery($channel_ids)
    {
        $channels = self::query()->whereIn('id', $channel_ids)->select();
        if ($channels->isEmpty()) {
            return fail('商品不存在');
        }
        $query = collect($channels);
        $success = array();
        $query->each(function (CouponProductChannel $productChannel) use (&$success) {
            $productChannel->butt = self::BUTT_CLOSE;       //对接状态设置为未对接
            $productChannel->product_id = 0;                      //关联面额清空
            $productChannel->brand_id = 0;                      //关联品牌清空
            $productChannel->relate_state = self::RELETE_STATE_WPP; //匹配状态设置为未匹配
            $productChannel->shelf_state = self::SHELF_STATE_WZ;   //上下架状态设置为未上架
            if ($productChannel->save()) {
                $success[] = $productChannel->id;
            }
        });
        if (empty($success)) {
            return fail('删除失败,请稍后再试');
        }
        return success('删除的商品id:[' . implode(',', $success) . ']');
    }


    public function scopeAvailableSale($query)
    {
        $query->where('status', CouponProductChannel::STATUS_ACTIVE)
            ->where('butt', CouponProductChannel::BUTT_ACTIVE)
            ->where('sku_type', CouponProductChannel::SKU_TYPE_ZC)
            ->where('relate_state', CouponProductChannel::RELETE_STATE_YPP)
            ->where('shelf_state', CouponProductChannel::RELETE_STATE_YPP);
    }

    /**
     * 返回亿奇达的充值规则数组
     * @return array
     */
    public function getBuyInputRuleAttr($value, $model)
    {
        $input = [];
        try {
            $template = $this->getTemplate($model['extend']);
            foreach ($template['regData'] as $k => $reg) {
                if (!in_array(strtoupper($reg), ['QQ', 'PHONE'])) {
                    //todo 充值类型只在乎QQ和手机，其他暂时不去校验了
                    unset($template['regData'][$k]);
                }
            }
            $input['input_msg'] = $template['tips'];
            $input['regData'] = $template['regData'];
        } catch (\Exception $e) {
        }
        return $input;
    }

    public function getTemplate($extend)
    {
        if (empty($extend)) {
            return [];
        }
        return current(json_decode(json_decode($extend)->template, true));
    }

}
